﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;

namespace SampleWpf.ViewModels
{

	public partial class SampleViewModel : ObservableObject, INotifyDataErrorInfo
	{

		//小写开头 or _开头 or m_开头
		/*[ObservableProperty]
		[NotifyPropertyChangedFor(nameof(FullName))]*/
		private string m_name = "这是个NAME";


		[ObservableProperty]
		private string? fullName;


		[ObservableProperty]
		[NotifyCanExecuteChangedFor(nameof(UpdateNameCommand))]
		private bool isUpdate;


		public string Name
		{
			get => m_name; set
			{
				m_name = value;
				ValidateProperty(nameof(Name));
			}
		}




		//Command.NotifyCanExecuteChanged


		/*		[RelayCommand(CanExecute = nameof(IsUpdate))]
				private void UpdateName()
				{
					this.Name = "Tom";
				}
		*/


		[RelayCommand(CanExecute = nameof(IsUpdate))]
		private async Task UpdateNameAsync()
		{
			await Task.Delay(10).ContinueWith((t) =>
			{
				this.Name = "Tom";
			});
		}


		public bool CanExcuteUpdateName()
		{
			return IsUpdate;
		}

		#region 校验部分
		public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
		private Dictionary<string, List<string>> errors;
		public bool HasErrors => errors != null && errors.Count > 0;



		public IEnumerable GetErrors(string? propertyName)
		{

			if (errors != null && errors.ContainsKey(propertyName))
				return errors[propertyName];
			return Enumerable.Empty<string>();
		}

		protected virtual void OnErrorsChanged(string propertyName)
		{
			ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
		}


		protected virtual void ValidateProperty(string propertyName)
		{
			List<string> propertyErrors = new List<string>();

			switch (propertyName)
			{
				case nameof(Name):
					if (string.IsNullOrEmpty(Name))
						propertyErrors.Add("Name的值不得为空");
					break;
			}

			if (propertyErrors.Any())
			{
				if (errors == null)
					errors = new Dictionary<string, List<string>>();

				errors[propertyName] = propertyErrors;
			}
			else
			{
				errors?.Remove(propertyName);
			}

			OnErrorsChanged(propertyName);
		}

		#endregion


	}
}

